package com.hzlx.config;

import com.hzlx.dto.ResultDto;
import com.hzlx.dto.UserDto;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

@RestController  // WebFlux, WebMVC
public class LoginController {
    @Resource
    LoginReactiveAuthenticationManager loginReactiveAuthenticationManager;
    @Resource TokenService tokenService;
    @PostMapping("/auth/login")
    public Mono<ResponseEntity<ResultDto<Object>>> login(@RequestBody UserDto user){
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getAccount(), user.getPassword());
        // 2. 委托给CustomAuthProvider认证
        return loginReactiveAuthenticationManager.authenticate(authentication)
                .map(auth -> {
                    // 3. 认证通过，生成JWT
                    List<String> authorities = auth.getAuthorities().stream()
                            .map(ga->ga.getAuthority())
                            .collect(Collectors.toList());
                    String token = tokenService.generateToken(auth.getName(),authorities);
                    UserDto userDto = (UserDto) auth.getDetails();
                    userDto.setPassword(null);
                    userDto.setToken(token);
                    userDto.setAuthorities(null);
                    return ResponseEntity.ok().body(ResultDto.<Object>builder().code("ok")
                            .data(userDto).build());
                })
                .onErrorResume(e -> {
                    e.printStackTrace();
                    // 4. 认证失败
                    return Mono.just(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build());
                });
    }
}
